package top.jandmla.excel.service.serviceImpl;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.jandmla.excel.service.MenusService;
import top.jandmla.excel.service.ShiroService;
import top.jandmla.excel.util.result.BaseResult;

import java.util.Map;

@Service
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private MenusService menusService;

    @Autowired
    private ShiroFilterFactoryBean shiroFilterBean;



    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=true,rollbackFor={Exception.class})
    public BaseResult<String> updatePermission() {
        synchronized (shiroFilterBean) {

            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterBean
                        .getObject();
            } catch (Exception e) {
                throw new RuntimeException(
                        "get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter
                    .getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver
                    .getFilterChainManager();

            // 清空老的权限控制
            manager.getFilterChains().clear();

            shiroFilterBean.getFilterChainDefinitionMap().clear();
            shiroFilterBean.setFilterChainDefinitionMap(menusService.loadFilterChainDefinitions());
            // 重新构建生成
            Map<String, String> chains = shiroFilterBean
                    .getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim()
                        .replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
            return BaseResult.success("权限更新成功！");
        }

    }
}
